package com.etonenet.service.system.security;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.etonenet.entity.system.UserLogin;
import com.etonenet.enums.userlogin.LoginSucc;
import com.etonenet.repository.system.security.UserLoginRepository;
import com.etonenet.util.DateUtil;
import com.etonenet.util.JsonUtil;

@Component
public class LoginFailHandler implements AuthenticationFailureHandler {

	@Resource
	UserLoginRepository userLoginEm;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {

		// 记录登录信息
		UserLogin ul = new UserLogin();
		ul.setIp(request.getRemoteAddr());
		ul.setIsSuc(LoginSucc.NO.getValue());
		ul.setLoginTime(DateUtil.getCurrentTimestamp());
		ul.setLoginName(request.getParameter("username"));
		ul.setPassword(request.getParameter("password"));
		userLoginEm.save(ul);

		Map<String, String> map = new HashMap<>();
		map.put("err", exception.getLocalizedMessage());
		String result = JsonUtil.objectToJson(map);

		OutputStream os = null;
		try {
			os = response.getOutputStream();
			os.write(result.getBytes());
			os.flush();
		} finally {
			if (os != null)
				os.close();
		}

	}

}
